package com.itheima.dfs;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.RequestContextUtil;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.feign.WmMaterialFeign;
import com.itheima.wemedia.pojo.WmMaterial;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dfs")
@Slf4j
public class FileController {

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private WmMaterialFeign wmMaterialFeign;

    /**
     * 上传文件
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    public ResultVo upload(MultipartFile multipartFile) {
        //获取请求的来源
        String header = RequestContextUtil.getHeader(SystemConstants.USER_HEADER_FROM);
        if (StringUtils.isEmpty(header)){
            throw  new LeadNewsException("拒绝上传");
        }
        //获取源文件的名字
        String filename = multipartFile.getOriginalFilename();
        String extension = StringUtils.getFilenameExtension(filename);

        try {
            //上传
            StorePath storePath = client.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), extension, null);
            //文件id
            String fullPath = storePath.getFullPath();
            log.info("上传文件：{} fileId: {}", filename,fullPath);
            if (SystemConstants.WEMEDIA_PIC.equals(header)){
                addWmMaterial(fullPath);
            }

            //为页面可以返回完整图片，要返回全路径
            ResultVo resultvo = ResultVo.ok(Collections.singletonMap("url", fdfsWebServer.getWebServerUrl() + fullPath));
            log.info("完整图片路径:{}",resultvo);
            return resultvo;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultVo.bizError("上传失败");
    }

    private void addWmMaterial(String fullPath) {
       //1.构建素材对象
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUrl(fullPath);
        wmMaterial.setIsCollection(0);
        wmMaterial.setCreatedTime(LocalDateTime.now());
        wmMaterial.setType(0);
        wmMaterial.setUserId(Long.parseLong(RequestContextUtil.getUserId()));

        ResultVo resultVo = wmMaterialFeign.add(wmMaterial);

        if (!resultVo.isSuccess()){
            throw  new LeadNewsException("文件上传失败");
        }
    }

    /**
     * 批量下载文件
     * @param fileIds
     * @return
     */
    @PostMapping("/download")
    public ResultVo<List<byte[]>> download(@RequestBody List<String> fileIds){
        // 有内容才下载
        if (!CollectionUtils.isEmpty(fileIds)){
            // 下载文件的字节数组处理器
            DownloadByteArray downloadByteArray = new DownloadByteArray();
            List<byte[]> collect = fileIds.stream().map(fileId -> {
                // 解析图片地址
                StorePath storePath = StorePath.parseFromUrl(fileId);
                // 下载文件为字节数组
                byte[] bytes = client.downloadFile(storePath.getGroup(), storePath.getPath(), downloadByteArray);
                return bytes;
            }).collect(Collectors.toList());
            return ResultVo.ok(collect);
        }
        return ResultVo.ok();
    }
}
